package com.zh.baselibrary.base;

import android.content.Context;

import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.rxjava.RxJavaHelper;
import com.zh.baselibrary.utils.LogUtils;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import io.reactivex.Observable;
import io.reactivex.functions.Predicate;



public class BasePresenter<V extends BaseView> {

    protected Reference<V> mViewRef;
    protected Reference<Context> mContextRef;

    public void attachModelView(V pView,Context context) {
//        mViewRef = new WeakReference<V>(pView);
        mViewRef = new SoftReference<>(pView);
        LogUtils.e("mViewRef赋值");
//        this.mContextRef = new WeakReference<>(context);
        this.mContextRef = new SoftReference<>(context);
        LogUtils.e("mContextRef赋值");
        attachModel(context);
    }
    public void attachModel(Context context){

    }


    public void onDetach() {
        if (null != mViewRef) {
            mViewRef.clear();
            mViewRef = null;
        }
        if (mContextRef != null) {
            mContextRef.clear();
            mContextRef = null;
        }
    }
    protected V getView() {
        LogUtils.e("mViewRef为空?:"+(mViewRef==null));
        return mViewRef.get();//获取View
    }
    protected Context getContext(){
        LogUtils.e("mContextRef为空?:"+(mContextRef==null));
        return  mContextRef.get();
    }

    //线程切换，绑定生命周期，过滤code不为0
    protected <T> Observable<BaseResp<T>> getObservable(Observable<BaseResp<T>> observable) {
        return observable.compose(RxJavaHelper.<BaseResp<T>>observeOnMainThread())
                .compose(mViewRef.get().<BaseResp<T>>bindToLife())
                .filter(new Predicate<BaseResp<T>>() {
                    @Override
                    public boolean test(BaseResp<T> tRespond) throws Exception {
                        if(!tRespond.isSuccess()){
                            if(!tRespond.isRepeat())
                               if(mViewRef.get()!=null){
                                   mViewRef.get().onHint(tRespond.getMsg());
                               }
                        }
                        return tRespond.isSuccess();
                    }
                });
    }
    //线程切换
    protected <T> Observable<BaseResp<T>> getObservableNotStop(Observable<BaseResp<T>> observable) {
        return observable.compose(RxJavaHelper.<BaseResp<T>>observeOnMainThread());
    }
    //线程切换，绑定生命周期
    protected <T> Observable<BaseResp<T>> getObservableNotFilter(Observable<BaseResp<T>> observable) {
        return observable.compose(RxJavaHelper.<BaseResp<T>>observeOnMainThread())
                .compose(mViewRef.get().<BaseResp<T>>bindToLife());
    }

}
